package l.l.w.leetcode.DegreeOfArray;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by llw on 2017/10/16.
 */
public class DegreeOfArray {

    public int findShortestSubArray(int[] nums) {
        HashMap<Integer, Entry> map = new HashMap<>();
        for(int i = 0; i < nums.length; ++i){
            if(map.containsKey(nums[i])){
                map.get(nums[i]).count+=1;
                map.get(nums[i]).end = i;
            }else{
                map.put(nums[i],new Entry(1,i,i));
            }
        }
        Iterator<Map.Entry<Integer, Entry>> iterator = map.entrySet().iterator();
        int maxLen = 0;
        while(iterator.hasNext()){
            int count = iterator.next().getValue().count;
            if(count >= maxLen){
                maxLen = count;
            }
        }
        iterator = map.entrySet().iterator();
        int minLen = Integer.MAX_VALUE;
        while (iterator.hasNext()){
            Entry entry = iterator.next().getValue();
            if(entry.count==maxLen){
                int len = entry.end-entry.start+1;
                if(len < minLen) minLen = len;
            }
        }
        return minLen;
    }
    class Entry{
        int count;
        int start;
        int end;
        Entry(int count,int start,int end){
            this.count = count;
            this.start = start;
            this.end = end;
        }
    }

    public static void main(String[] args) {
        int[] nums = {1,2,2,3,1,4,2};
        int result = new DegreeOfArray().findShortestSubArray(nums);
        System.out.println(result);
    }
}
